package com.googlecode.wickedforms.xvergabe.modelers;

import java.awt.List;
import java.util.ArrayList;
import java.util.Locale;

import org.apache.xmlbeans.XmlObject;
import org.xvergabe.xsd.forms.components.x20.AbstractComponent;
import org.xvergabe.xsd.forms.components.x20.FormDocument.Form;
import org.xvergabe.xsd.forms.components.x20.FormMetaData;
import org.xvergabe.xsd.forms.components.x20.FormMetaData.ActivationToggle;
import org.xvergabe.xsd.forms.components.x20.OrSection;
import org.xvergabe.xsd.forms.components.x20.RoleType;
import org.xvergabe.xsd.forms.components.x20.Section;
import org.xvergabe.xsd.forms.components.x20.XorSection;

import com.googlecode.wickedforms.model.FormModel;
import com.googlecode.wickedforms.model.elements.AbstractFormElementModel;
import com.googlecode.wickedforms.xvergabe.modelers.components.OrSectionModeller;
import com.googlecode.wickedforms.xvergabe.modelers.components.SectionModeller;
import com.googlecode.wickedforms.xvergabe.modelers.components.XorSectionModeller;

public class FormModeller implements XmlModeller<Form, FormModel> {

	private final XorSectionModeller xorSectionModeller;
	private final OrSectionModeller orSectionModeller;

	private final FormModel model;

	public FormModeller(final String formTitle) {
		this.model = new FormModel(formTitle);
		this.xorSectionModeller = new XorSectionModeller(this);
		this.orSectionModeller = new OrSectionModeller(this);
		
	}

	@Override
	public FormModel createModelFromXml(final Form xmlObject,
			final Locale lang, final RoleType.Enum sellerMode) {

		int sectionIndex = 1;
		for (XmlObject formElement : xmlObject.selectPath("./*")) {

			if (formElement instanceof FormMetaData) {
				continue;
			}

			AbstractComponent component = (AbstractComponent) formElement;

			if (component instanceof Section) {
				SectionModeller modeller = new SectionModeller(this, sectionIndex);
				this.model.add(modeller.createModelFromXml((Section) component,
						lang, sellerMode));
			} else if (component instanceof XorSection) {
				this.model.add(this.xorSectionModeller.createModelFromXml(
						(XorSection) component, lang, sellerMode));
			} else if (component instanceof OrSection) {
				this.model.add(this.orSectionModeller.createModelFromXml(
						(OrSection) component, lang, sellerMode));
			} else {
				throw new RuntimeException(
						"Unknown component! Cannot create model for xml component of type "
								+ component.getClass());
			}
			sectionIndex++;
		}

		return this.model;
	}
}
